/**
 * @author klv
 */

var QS_Screener=function(containDom,callback){
    this.curTabID="ST";
    this.filters={};
	this.domMap={};
    this.container=containDom;
    this.cacheDataofDrp={};
    this.lastHeightChange=0;
    this.firstTag=true;
	var self=this;
    this.callback={};
    $.extend(self.callback,callback);
    this.currentSearchItemID=-1;
	this.staticValue={
		viewTab:28,
		operateBar:24,
		gridMinWidth:430,
		pageBar:30,
		vertical:0,
		winTitle:26,
		horizontal:0,
		leftMenuWidth:245
	};
    this.config = {
        canExport: true,
        navSize:10,
        pageSize: 40,
		dragable:false,
		clickTicker:true,
        isDefault:false,
        needOperBar:true,
        exportWLMax: 500,
        IDRMax:100,
		dropDown:"ST",//default ddl
        exportExcelMax: 2000,
        exportXMLMax: 2000,
        fixHeight:true,
        isAPI:true,
        sortbyall:true,
        showLoading:true,
        needFile:true
    };
    this.cacheData={};
    this.cacheColsData={};
    this.sortCache=String.format("{0}:1",this.tickerCode);
    this.isCheckAll=false;
    this.selectedData=[];
    this.unselectedData=[];
    this.win=null;
};
QS_Screener.prototype=$.extend(true,{},QS_BaseSearch,QS_screenerConfig,{
    init:function(cfg){
        $.extend(this.config,cfg);
        if(!isNaN(this.config.padingH)){
            this.staticValue.horizontal=parseFloat(this.config.padingH);
        }
        if(!isNaN(this.config.padingV)){
            this.staticValue.vertical=parseFloat(this.config.padingV);
        }
        if(!this.config.clickTicker){
            // set render is null
            if(!this.searchField){
                this.searchField=this._getNullRenderField();
            }else{
                $.extend(true,this.searchField,this._getNullRenderField());
            }
        }
		this.baseSearchInit();
        var loadingEl='<div class="x-tool x-tool-loading" title="Loading"><img src="'+((typeof QS_Theme!='undefined'&&QS_Theme=="black")?"//rtqimg.morningstar.com/theme/black/loading.gif":"//rtqimg.morningstar.com/img/loading.gif")+'" />Loading...</div>';
        if (this.config.isAPI) {
              this.el=$(this._getHtml()).appendTo(this.container);
			  this.loadingEl = this.el.find(".qs-search-loading").append(loadingEl);
        }
        else{
            var self=this;
            this.win = new Util.RtqWindow(document.body, {
                windowReady: function(obj){
                    obj.setHtml(self._getHtml());
                    self.el = obj.el.find(".qs-screener");
					self.container=self.el.parent();
                },
                beforeClosed: function(){
					
                },
                onResized: function(win, width, height){
                    self.changeOutSize(width, height);                    
                }
            }, {
                title: "Screener",
                top: 50,
                width: this.config.width,
                height: this.config.height,
                minWidth:this.staticValue.leftMenuWidth + this.staticValue.gridMinWidth, //the window's min width
                minHeight:400, //the window's min height
                resizable: true,
                isGlobal: true,
                hasSettingPanel: false,
                closeAction: 'hide'
            });
            this.win.loadingEl = $(loadingEl+"Loading...").appendTo(this.win.el.find('div.win-hd'));
            if(this.config.canExport&&this.config.needFile&&typeof componentFileMenu!='undefined'){
                this.fileMenuObj = new componentFileMenu($(this.win.el.find('div.win-operator')),this.win,{detach:false},
                    [QSPC.checkPermission(25.01)?{txt:"Investment Detail Report",val:"idr"}:null,
                    {txt:"Export",val:"",subMenu:[
                        {txt:"PDF",val:"pdf"},
                        /*{txt:"XML",val:"xml"},*/
                        {txt:"Excel",val:"xls"}]
                    }],this.screenerWidgetType||"25");
                this.win.fileMenuCallback=function(type){
                    self._exportToFile(type);
                };
            }
            if (typeof rtqWindowGroup != 'undefined') {
                rtqWindowGroup.register(this.win);
            }
        }
        if (this.config.fixHeight) {
            this.screenerLeftScroll = new Util.ScrollPanel(this.el.find('.qs-screener-leftMenu'), {
                showY: true
            });
        }
        this.checkboxDialog = new Search_buttonDialogCheckBox($(".qs-screener"), 'checkbox',this);
        this.genDropDownList();
		if(this.config.dropDown){
			this.curTabID=this.config.dropDown;
		}
		this.genDataGrid();
		this.genPage();
		var self=this;
		if (this.config.needOperBar) {
			this.saveSearch=new QS_SearchSave(this.templeteType,{
				onSaveBefore:function(){
					self.onShowLoading();
				},
				onSaveAfter:function(sucess,id){
					if(sucess){
                        if(!self.config.isAPI&&QSPC.checkPermission(0.08)){
                            QS_watchlistDataManager.clearScreenerCache(id);
                            QS_watchlistDataManager.saveHoldings(id);
                        }
                    }
					self.onHideLoading();
				},
				onSaveasBefore:function(){
					self.onShowLoading();
				},
				onSaveasAfter:function(sucess,id,name){
					if(sucess){
						self.currentSearchItemID =id;
						self.operateBar.setButtonDisable("save", false);
                        self._setDefaultButton();
                        self.operateBar.setName(name);
                        if(!self.config.isAPI&&QSPC.checkPermission(0.08)){
                            QS_watchlistDataManager.resetStatus("screener");
                            QS_WatchlistStartUpManager.sync();
                        }
					}
					self.onHideLoading();
				},
				onDeleteBefore:function(){
					self.onShowLoading();
				},
				onDeleteAfter:function(sucess,id){
					if(sucess){
						if(self.currentSearchItemID == id){
							self.curTabID="ST";
							self.selectMySearch();
						}
                        if(!self.config.isAPI&&QSPC.checkPermission(0.08)){
                            QS_watchlistDataManager.resetStatus("screener");
                            QS_watchlistDataManager.deleteWatchlist(id);
                        }
					}
					self.onHideLoading();
				},
				onDefaultBefore:function(){
					self.onShowLoading();
				},
				onDefaultAfter:function(sucess,id){
					if(sucess){self._setDefaultButton();}
					self.onHideLoading();
				},
				onClose:function(){
					self.operateBar.clearOn();
				}
			});
			this.genOperatoeBar();
		}
        if (this.config.openID&&this.config.openID!="-1") {
            this.selectMySearch(this.config.openID);
        }else if(this.config.trigger&&!$.isEmptyObject(this.config.trigger)){
            this.openBy3thFilter(this.config.trigger);
        }else {
            this.selectMySearch(this.config.isDefault=='true'?Terminal.getConfig("defaultCriterion"):'-1');
        }
        this.staticValue.viewTab=this.el.find(".qs-screener-resultview").outerHeight(true);
        this.staticValue.operateBar=this.el.find(".qs-screener-resultview").outerHeight(true);
        this._bindEvent();
    },
    _getNullRenderField:function(){
        var fields={};
        fields[this.keyWordCode]={renderer:null};
        fields[this.tickerCode]={renderer:null};
        return fields;
    },
    loadHandler:function(){
        if(typeof this.callback.onLoad=='function'){
            this.callback.onLoad({
                component: "screeners",
                height: this.el.height(),
                minWidth : this.staticValue.leftMenuWidth+this.staticValue.gridMinWidth
            });
        }
		this.firstTag = false;
    },
    show:function(){
        if(this.win!=null){
            this.win.show();
        }else{
            this.el.show();
        }
    },
    hide:function(){
        if(this.win!=null){
            this.win.hide();
        }else{
            this.el.hide();
        }
    },
    heightChangeHandler:function(){
        if(typeof this.callback.onHeightChange=='function'){
            var height=this.el.height();
            if(this.lastHeightChange!=height){
                this.callback.onHeightChange({
                     component: "screeners",
                     height:height
                });
                this.lastHeightChange=height;
            }
        }
    },
    setScreenerScroll: function(heightcontainer){
        if (typeof this.screenerLeftScroll != 'undefined' && this.screenerLeftScroll != null) {
            var headerHeight = $(".qs-gd2 .hd").outerHeight(true);
            var fixedheight = this.el.find('.qs-screener-fixedfilter').outerHeight(true);
            var height = this.el.find('.qs-screener-universe').outerHeight(true);
            this.screenerLeftScroll.reSize(this.staticValue.leftMenuWidth, (heightcontainer||this.container.innerHeight()) -this.staticValue.vertical-fixedheight - height - headerHeight);
        }
    },
    openBy3thFilter:function(trigger){//by 3th trigger
        if (trigger.secType) {
			if(this.curTabID!=trigger.secType){
                this.clearSelectedItem();
                this.curTabID=trigger.secType;
                this.dropDownList.setTextValue(null, this.curTabID);
            }
        }
        this.genGroupBox();
        this.genViewTab();
        this.bindFilterData(trigger.selected);
        this.currentSearchItemID = -1;
		if (this.config.needOperBar) {
			this.operateBar.setButtonDisable("save", true);
			this._setDefaultButton();
			this.operateBar.setName();
		}
        
    },
    selectMySearch:function(id){
		if(typeof id != 'undefined'&&id!=null && id != "-1"&&id==this.currentSearchItemID) return;  // change by Jacye.
        var self=this;
        self.cacheData={};
        self.isCheckAll=false;
        self.selectedData=[];
        self.unselectedData=[];
        if (typeof id != 'undefined'&&id!=null && id != "-1") {
            self.saveSearch.getSearchData(id, function(data){
                if (data == null) {
                    self.selectMySearch();   
                }
                else {
					if(self.curTabID!=data.tabID){
						self.clearSelectedItem();
						self.curTabID=data.tabID;
						self.dropDownList.setTextValue(null, data.tabID);
					}
                    if (data.sortfield) {
                        self.sortCache = data.sortfield + ":" + data.sorttype;
                    }
                    self.genGroupBox();
                    self.genViewTab();
                    self.bindFilterData(data.selected);
                    self.currentSearchItemID = id;
					if (self.config.needOperBar) {
						self.operateBar.setButtonDisable("save", false);
						self._setDefaultButton();
						self.operateBar.setName(data.title||self.saveSearch.getSearchNameByID(id));
					}
                }
            });
        }else{
            this.currentSearchItemID = -1;
            this.dropDownList.setTextValue(null,this.curTabID);
            this.genGroupBox();
            this.genViewTab();
            this.bindFilterData({});
			if (this.config.needOperBar) {
				this.operateBar.setButtonDisable("save", true);
				this._setDefaultButton();
				this.operateBar.setName();
			}
        }
    },
    bindFilterData:function(sData){  // change by Jacye
	    var savedData = $.extend(true,{},sData);
        this.onShowLoading();
        var self=this;
        this.getDynamicData(this._getFilterField(this.curTabID),function(datamap){
            //self.clearSelectedItemValue();
			var code=null,fixedCriteria=self.fixedCriteria,tempData=null;
			for(var i=0,l=fixedCriteria.length;i<l;i++){//fix filter
				code=fixedCriteria[i],tempData=savedData[self.getCode(code)];
				if(self.filters[code]&&self.filters[code].selected) self.filters[code].selected = []; // clear the key words.
				if (self.firstTag) {
					self.filters[code] = {
						status: "fix",
						selected: []
					};
					$.extend(true, self.filters[code], self.selectedItem[code]);
				}
				if (tempData) {
					if (!self._isEmptyArray(tempData)) {
						self.filters[code].selected = tempData;
					}
					delete savedData[code];  // Note: saveData is an object.
				}
			}
            self._genFixedFilter();
			for(var code in savedData){
				self.filters[code]={status:"dynamic",selected:savedData[self.getCode(code)]};
				$.extend(true,self.filters[code],self.selectedItem[code]);
			}
			//add a default filter
			//self.filters[self.securityTypeCode]={selected:[self.curTabID],status:"hide"};
			Util.DelayRun('bindGroupBox.screener', function(){
				self._bindDynamicFilterDOM(self.groupBox.currentGroup.id);
			}, 0, this);
            self.searchOperate(0);
        },function(){
			Util.message(QS_Lang.screener.searchfailed);
            self.onHideLoading();
		});
    },
	_bindDynamicFilterDOM:function(id){
		var temp=null,code,groupBoxData = this.getGroupBoxDetail(this.curTabID,id);
        for(var i=0,l=groupBoxData.length;i<l;i++){
			code=groupBoxData[i];
            if(!this.checkPermission(code)) continue;
			if (!this.filters[code]) {
				this.filters[code]={status: "dynamic",selected:[]};
				$.extend(true,this.filters[code],this.selectedItem[code]);
			}
			this._addRow(this.groupBox.getGroup(id).bd,this.filters[code]);
        }
        this.setScreenerScroll();
	},
    _genFixedFilter:function(){
        var code=null,fixedCriteria=this.fixedCriteria;
        for(var i=0,l=fixedCriteria.length;i<l;i++){
            code=fixedCriteria[i];
			if (!this.domMap[code]) {
				this._addRow(this.el.find(".qs-screener-fixedfilter"), this.filters[code]);
			}else{
				this.domMap[code].dom.filter.setDefault(this.filters[code].selected);
			}
        }
    },
    _clearRow: function(key){
	    this.filters[key]["selected"] = [];
        this.domMap[key].dom.filter.reset();
    },
    _getFilterField:function(drpid){
        var data=this.groupBox.data;
        if (!this.cacheDataofDrp[drpid]) {
            var datalist=[].concat([this.securityTypeCode],this.fixedCriteria,Search_DefaultData.search_DataKey);
            for (var i = 0, l = data.length; i < l; i++) {
                var datafilter = this.getGroupBoxDetail(drpid,data[i].id);
                datalist=datalist.concat(datafilter);
            }
            var tempView=this.getViewColumnData(drpid);
            for(var viewid in tempView){
                 datalist=datalist.concat(tempView[viewid]);
            }
            this.cacheDataofDrp[drpid]=datalist;
        }
        return  this.cacheDataofDrp[drpid];
    },
    _addRow: function(containerDOM,data){
		var code=data.val,status=data.status,rowDOM=null;
        if (this._existKey(code))
            return;
        var annotation=Search_DefaultData.annotation[code]?'title="' + Search_DefaultData.annotation[code] + '" style="cursor:default;"':'';
        var showHelp=Search_DefaultData.annotation[code]?'<span class="helpicon"></span>':'';
        var tempRowHtml = '<div class="qs-screener-filter">';
        tempRowHtml += '<div class="qs-screener-item qs-screener-filtername" '+annotation+'><span class="content">' + (data.txt) + '</span>' + this._addOperateColnumHtml()+showHelp+'</div>';
        tempRowHtml += '<div class="qs-screener-item qs-screener-filtervalue"></div>';
        tempRowHtml += "</div>";
        rowDOM=$(tempRowHtml).appendTo(containerDOM);
		rowDOM.data("code",code);
        this.domMap[code] = {
			dom: rowDOM,
			status: status
		};
        this._setValueListDOM(data, rowDOM);
        rowDOM.find('.content').ellipsis(false,0);
    },
    removeAllRow: function(){
		for(var code in this.filters){
			if(this.filters[code].status!="fix"){
				delete this.filters[code];
				if (this.domMap[code]) {
					delete this.domMap[code];
				}
			}
		}
    },
    _existKey:function(code){
		return this.domMap[code]?true:false;
    },
    _addOperateColnumHtml: function(){
        var tempOperHtml = '<a href="javascript:void(0);" class="qs-screener-reset">reset</a>';
        return tempOperHtml;
    },
    _bindEvent: function(){
        var self = this;
        $(".qs-screener-fixedfilter,.qs-screener-leftMenu").bind("click", function(e){
            //e.stopPropagation();
            if (e.target.tagName.toUpperCase() == "A") {
                var obj = $(e.target);
                var rowObj = obj.closest(".qs-screener-filter");
                if (obj.hasClass("qs-screener-reset")) {
                    self._clearRow(rowObj.data("code"));
                    self.delaySearch();
                }
            }
        });
    },
    _setValueListDOM: function(rowData, rowDOM){
        var self = this,rowObj=null,cellDOM=rowDOM.find('.qs-screener-filtervalue');
		switch(rowData.renderType){
			case "sld":
				cellDOM.addClass('qs-search-slider');
	            if (rowData.selectable) {
	                var max=rowData.selectable.max, min=rowData.selectable.min;
	                if (parseFloat(max)-parseFloat(min)>0) {
	                    rowDOM.filter= new QS_SliderFilter(cellDOM,{scales: [min, max]},{
	                        onDragEnd: function(start, end){
	                            var startValue=start.value;
	                            rowData.selected[0] = Math.max(startValue,min);
	                            var endValue=end.value
	                            rowData.selected[1] = Math.min(endValue,max);
	                            self.delaySearch();
	                        }
	                    });
	                    rowDOM.filter.setDefault(rowData.selected);
	                }else{
	                    cellDOM.append("<span>No data available</span>");
	                }
	            }else{
	                cellDOM.append("<span>No data available</span>");
	            }
				break;
			case "cbl":
				rowDOM.filter = new QS_CheckBoxFilter(cellDOM, {
					defaultValue: rowData.selected
				}, {
					onClick: function(e){
						e.stopPropagation();
						self.checkboxDialog.setRow(rowData, rowDOM.filter.getDom());
						self.checkboxDialog.show();
					}
				});
				break;
			case "rbl":
			    rowDOM.filter= new QS_RadioButtonFilter(cellDOM,rowData.selectable,{
                    defaultSelected:rowData.selected
                },{
                    onClick: function(v, item){
                        if (item.isSelected) {
                            rowData.selected.push(v);
                        }
                        else {
                            var index = $.inArray(v, rowData.selected);
                            if (index != -1) {
                                rowData.selected.splice(index, 1);
                            }
                        }
                        self.delaySearch();
                    }
                });
				break;
			case "dpl":
			    rowDOM.filter = new QS_DropDownFilter(cellDOM, {defaultValue:rowData.selected}, {
					onMouseOver: function(e){
						if (self.checkboxDialog._timeOut) {
							clearTimeout(self.checkboxDialog._timeOut);
						}
						self.checkboxDialog.setRow(rowData,rowDOM.filter.getDom(), rowData.renderType,self.win?{left:self.win.cfg.left,top:self.win.cfg.top+self.staticValue.winTitle}:{left:0,top:0});
						self.checkboxDialog.show();
					},
					onMouseOut: function(){
						self.checkboxDialog.hide();
					}
				});
				break;
			case "str":
                rowDOM.filter=new QS_MStarFilter(cellDOM, {score:rowData.selected}, {
                    onClick: function(score){
                        rowData.selected[0] = score;
                        self.delaySearch();
                    }
                });
				break;
			case "msb":
                cellDOM.addClass('qs-search-sytlebox');
//				var trigger = $('<div class="qs-search-sytlebox"></div>').appendTo(cellDOM).click(function(e){
//					if (self.stylebox == null) {
//	                    self.stylebox = new Search_styleboxDialog($('.qs-search'));
//					}
//					self.stylebox.setInit(rowData, trigger[0].obj);
//				});
				rowDOM.filter = new QS_MStyleBoxFilter(cellDOM, {
				    type:this.curTabID,
				    defaultCheck:rowData.selected
				}, {
				    onCellCheck: function(cell, ctf){
				        rowData.selected = ctf['index'];
				        self.delaySearch();
				    },
				    onCellUnCheck: function(cell, ctf){
				        rowData.selected = ctf['index'];
				        self.delaySearch();
				    },
				    onReSet: function(ctf){
				        rowData.selected = ctf['index'];
				        self.delaySearch();
				    }
				});
                break;
			case "ipt":
                rowDOM.filter=new QS_InputFilter(cellDOM,{defaultValue:rowData.selected},
				{onKeyup:function(val){
	                    rowData.selected[0] = val;
	                    self.delaySearch();
				    }
				});
				break;
			default:
				break;
		}
    },
    changeOutSize:function(w,h){
        var minWidth= this.staticValue.leftMenuWidth + this.staticValue.gridMinWidth;
        if(this.config.isAPI){
            w = this.config.width||w||this.container.innerWidth();
            h = this.config.height||h||this.container.innerHeight();
        }else{
            //if it is terminal, the height of win-bd is static
            w = w||this.container.parent().innerWidth();
            h = h||this.container.parent().innerHeight();
            h -=this.staticValue.winTitle;
            this.el.css({
                width: "auto"
            });
        }
        var resultH = h - this.staticValue.vertical-this.staticValue.viewTab- this.staticValue.pageBar - (this.config.needOperBar?this.staticValue.operateBar:0);
        var resultW =w-this.staticValue.leftMenuWidth-this.staticValue.horizontal;

        if (this.config.fixHeight) {
            this.dataGrid.resize(resultW, resultH);
        } else {
            this.dataGrid.resize(resultW, null);
        }
		this.setScreenerScroll(h);
    },
	onShowLoading:function(){
        if(this.config.showLoading){
            if (this.win) {
                this.win.titleEl.find('h3').hide();
                this.win.loadingEl.show();           
                if(this.win.settingPanelObj){
                    this.win.settingPanelObj.setDisabled();
                }
                this.win.el.addClass('rtq-win-onloading');         
                this.win.contentMask.show();
            }else{
                this.loadingEl.show();
            }
        }
    },
    onHideLoading:function(){
        if(this.config.showLoading){
            if (this.win) {
                this.win.titleEl.find('h3').show();
                this.win.loadingEl.hide();
                if(this.win.settingPanelObj){
                    this.win.settingPanelObj.setEnabled();
                }
                this.win.el.removeClass('rtq-win-onloading'); 
                this.win.contentMask.hide();
            }else {
                this.loadingEl.hide();
            }
        }
    },
    _searchCallback:function(currenttab,page,start,total,data){
        if(!this.cacheColsData[currenttab]){
            this.cacheColsData[currenttab]={};
        }
        if(!this.cacheColsData[currenttab][this.currentView]){
            var defaultCols=this.getViewColumnData(currenttab,this.currentView);
            var colstemp=this.getViewCols(defaultCols);
            this.cacheColsData[currenttab][this.currentView]=this._setOperateCol(colstemp);
        }
        this.reBindDataGrid(this.cacheColsData[currenttab][this.currentView],data);
        if(total!=null){
            var pageConfig={curPage:page}
            pageConfig.total=total;
            this.pageBottom.rebind(pageConfig);
        }
        this.onHideLoading();
    },
    searchOperate:function(start,sortfield,sorttype){
        this.onShowLoading();
        var page=Math.floor(start/this.config.pageSize)+1;
        var sort=this.sortCache.split(":");
        if(this.cacheData[this.curTabID]&&this.cacheData[this.curTabID][page]){
            this._searchCallback(this.curTabID,page,start,null,this.cacheData[this.curTabID][page]);
            this.dataGrid.setSortICON(this.getCode(sort[0]),sort[1]=="1"?"ASC":"DESC");
        }else{
            var self=this;
            self.getSearchResult(function(data,total){
                //cols is availiable
                self.cacheData[self.curTabID]={};
                self.cacheData[self.curTabID][page]=data;
                if(!self.cacheData[self.curTabID]){
                    self.cacheData[self.curTabID]={};
                }
                self._searchCallback(self.curTabID,page,start,total,data);
                //cache sort statu
                if (sortfield && sorttype) {
                    self.sortCache = sortfield + ":" + sorttype;
                }
                self.dataGrid.setSortICON(self.getCode(sortfield||sort[0]),(sorttype||sort[1])=="1"?"ASC":"DESC");
            },start,self.config.pageSize,self._getFilterField(self.curTabID),self.getCode(sortfield||sort[0]),sorttype||sort[1]);
        }
    },
    _setOperateCol:function(cols){
        var colsadd=[];
        $.extend(true,colsadd,cols);
        var self=this,length=colsadd.length;
        //add the gridconfig
        if(this.config.sortbyall){
            for(var i=0;i<length;i++){
                colsadd[i].refetch=true;
            }
        }
        if(colsadd.length>0&&this.config.canExport){
            colsadd.unshift({
                header: '<a herf="javascript:void(0);" class="qs-search-selectall">'+(this.isCheckAll?"Unselect":"Select")+'</a>',
                dataIndex: self.indexColKey,
                width: 60,
                align: 'center',
                sortable: false,
                renderer: function(txt){
                    return self._isSelected(txt)?'<input key="' + txt + '" type="checkbox" checked>':'<input key="' + txt + '" type="checkbox">';
                }
            });
        }
        return colsadd;
    },
    reBindDataGrid:function(cols,data){
        this.dataGrid.setColumnCfg(cols);
        this.dataGrid.reBindData(data);
		if(cols.length!=0&&data.length==0){
			this.el.find(".qs-no-info").show();
		}else{
			this.el.find(".qs-no-info").hide();
		}
        this._reBindGridEvent();
    },
    _isSelected:function(indexColKeyValue){
        if (this.isCheckAll) {
            var data = this.unselectedData;
            for (var l = data.length, i = 0; i < l; i++) {
                if (data[i][this.indexColKey] == indexColKeyValue) {
                    return false;
                }
            }
            return true;
        }
        else {
            var data = this.selectedData;
            for (var l = data.length, i = 0; i < l; i++) {
                if (data[i][this.indexColKey] == indexColKeyValue) {
                    return true;
                }
            }
            return false;
        }
    },
    _exportToFile:function(type){
        var data={idr:{txt:"Investment Detail Report"},pdf:{txt:"PDF"},xls:{txt:"Excel"},xml:{txt:"XML"},wl:{txt:"WatchList"}};
        data=data[type];
        var total=this.pageBottom.config.total;
        var needExportCount;
        if(this.isCheckAll){
            needExportCount=total-this.unselectedData.length;
        }else{
            needExportCount=this.selectedData.length;
        }
        var isOverMax=false;
        var Max;
        switch (type) {
            case "idr":
                 Max=this.config.IDRMax;
                 break
            case 'xls':
                 Max=this.config.exportExcelMax;
                 break;
            case 'wl':
                 Max=this.config.exportWLMax;
                 break;
            case 'pdf':
            case 'xml':
                 Max=this.config.exportXMLMax;
                 break;
            default:
                 break;
        }
        isOverMax = needExportCount > Max;
        if (needExportCount == 0) {
            Util.message(QS_Lang.screener.norecords);
        }
        else {
            if (isOverMax) {
                Util.message(String.format(QS_Lang.screener.overmax, data.txt, Max));
            }
            else {
                var self = this;
                Util.confirm(String.format(QS_Lang.screener.exportconfirm,data.txt,needExportCount,needExportCount>1?"s":""), function(b){
                    if (b) {
                        var sort=self.sortCache.split(":");
						self.exportData(type,self.isCheckAll,self.getCode(sort[0]),sort[1],total);
                    }
                }, {
                    title: "Report Confirm"
                });
            }
        }
    },
	exportData:function(type,isAll,sortfield,sorttype,total){
		var globequery=this._getQueryCondition(),unselectedStr=null,viwCols=this.getViewColumnData(this.curTabID,this.currentView);
		var data={
			file: type,
			gridcol: $.toJSON(this.getViewCols(viwCols)),
			name:"SearchReport"
		}
		if(sortfield){
			if(sortfield==this.keyWordCode) sortfield=this.replaceKeyWordCode;
			data["sortfield"]=sortfield;
        }
        if(sorttype){
            data["sorttype"]=sorttype;
        }
		var specialCode=this.PIdCode;
		if (this.curTabID=='FE'&&type=='idr'){//if export idr and securitytype is fe
            specialCode=this.SIdCode;
        }
		if(isAll){
//			if (this.curTabID=='FE'&&type=='idr'){//if export idr and securitytype is fe
//				specialCode=this.SIdCode;
//			}
			if(globequery.query['Keywords'].length == 0){
	            Util.message(QS_searchConfig.ExportPrompt);
				return;
	        }
			var unselectedStr=[];
			for(var i=0,l=this.unselectedData.length;i<l;i++){
	            unselectedStr.push(this.unselectedData[i][this.PIdCode]);
	        }
			data.type='all';
			data.total=total;
			data.query = $.toJSON(globequery.query),
			data.unselected=$.toJSON(unselectedStr);
			data.file=type;
			data.cols=$.toJSON({
	                Columns: [].concat([this.PIdCode],viwCols)
	            });
		}else{
			data.type='sel';
			data.selected=$.toJSON(this.selectedData);
		}
        if (type=='idr'||type=='wl') {//only export sID/pID
            data.exportField=specialCode;
            if (typeof data.cols != 'undefined') {
				data.cols = $.toJSON({
	                Columns: [specialCode]
				});
            }
            this.exportToOtherComponent(data,type);
        }
        else {
            if(type == 'pdf'){
                data.securityType=this.curTabID=="ST"?"Stock":"Exchange Traded Fund";
            }
            DBHelper.openWindowWithPost(data);
        }
	},
	exportToOtherComponent:function(data,type){
        data.file="wl";
        var instid = api_common_openwindow.getLocationArg()["instid"];
        DBHelper.post(DBHelper.URLs.searchExport,data, function(o){
            if (o == 'false') {
                Util.message(QS_searchConfig.ExportFailed);
            }
            else {
                switch (type) {
                    case "wl":
                        var tempurl = String.format("api.jsp?instid={0}&module=watchlist&data=streaming", instid);
                        api_common_openwindow.openWindow(String.format("{0}&symbols={1}", tempurl, o), "WatchList");
                        break;
                    case "idr":
                       SiteBuilder_firstLoadLoginPage();
                       var i=0,symbols=o.split(',').join('|');
                       var self=this;
                       if (STATIC_VAR.marketIndexSessionExists == false) {
                           this.interval = setInterval(function(){
                                if (i < 10) {
                                    i++;
                                    if(STATIC_VAR.marketIndexSessionExists ==true){
                                        api_common_openwindow.openWindow("https://awrd.morningstar.com/SB/Data/GetIDRDetailReport.aspx?disclosure=1&universe=10&datasrc=AWD&stkprem=1&instid=SBDEMO&lang=en-US&tool=Screener&symbol="+symbols,"IDR");
                                        clearInterval(self.interval);
                                    }
                                } else {
                                    clearInterval(self.interval);
                                }
                           }, 1000);
                        }else{
                             api_common_openwindow.openWindow("https://awrd.morningstar.com/SB/Data/GetIDRDetailReport.aspx?disclosure=1&universe=10&datasrc=AWD&stkprem=1&instid=SBDEMO&lang=en-US&tool=Screener&symbol="+symbols,"IDR");
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    },
    _setDefaultButton:function(){
        if(this.currentSearchItemID==-1||Terminal.getConfig("defaultCriterion")==this.currentSearchItemID){
            this.operateBar.setButtonDisable("default",true);
        }
        else{
            this.operateBar.setButtonDisable("default",false);
        }
    },
    _refreshGrid:function(data){
        this.dataGrid.reBindData(data);
        this._reBindGridEvent();
    },
    _reBindGridEvent:function(){
        var selectAllCell = this.dataGrid.header.row.cells[this.indexColKey];
        var self=this;
        if(selectAllCell){
            selectAllCell.el.unbind("click").click(function(e){
                e.stopPropagation();
                self.isCheckAll=!self.isCheckAll;
                self.unselectedData=[];
                self.selectedData=[];
                if(self.isCheckAll){
                    $(this).find(".qs-search-selectall").text("Unselect");
                }else{
                    $(this).find(".qs-search-selectall").text("Select");
                }
                for (var r in self.dataGrid.rows) {
                    self.dataGrid.rows[r].cells[self.indexColKey].el.find('input')[0].checked = self.isCheckAll;
                }
            });
            self.dataGrid.el.find('input').click(function(e){
                if(!$(this).hasClass("qs-grid-selectall")){
                    var txt=$(this).attr('key');
                    if (self.isCheckAll) {
                        if (!this.checked) {
                            var data = self.unselectedData;
                            for (var l = data.length, i = 0; i < l; i++) {
                                if (data[i][self.indexColKey] == txt) {
                                    return;
                                }
                            }
                            self.unselectedData.push(self.dataGrid.rows[txt].data);
                        }else{
                            for(var i=0,l=self.unselectedData.length;i<l;i++){
                                if(self.unselectedData[i][self.indexColKey]==txt){
                                    self.unselectedData.splice(i,1);
                                    break;
                                }
                            }
                        }
                    }else{
                        if(this.checked){
                            var data = self.selectedData;
                            for (var l = data.length, i = 0; i < l; i++) {
                                if (data[i][self.indexColKey] == txt) {
                                    return;
                                }
                            }
                            self.selectedData.push(self.dataGrid.rows[txt].data);
                        }else{
                            for(var i=0,l=self.selectedData.length;i<l;i++){
                                if(self.selectedData[i][self.indexColKey]==txt){
                                    self.selectedData.splice(i,1);
                                    break;
                                }
                                
                            }
                        }
                    }
                    if(typeof (self.callback.onClickCheckbox)=='function'){
                        self.callback.onClickCheckbox({
                            component:"screeners",
                            ticker:self.dataGrid.rows[txt].data[self.getCode(self.tickerCode)],
                            pid:self.dataGrid.rows[txt].data[self.indexColKey],
                            check:this.checked
                        });
                        //self.dataGrid.rows[txt],this.checked);
                    }
                }
            }
            );
        }
    },
    _getQuickTakeURL:function(ticker){
        var data={"module":"research","symbol":ticker},urlCfg=api_common_openwindow.getLocationArg();
        data.submodule="quicktake_"+(this.curTabID=='FE'?"etf":"st");
		for(var attr in urlCfg){
            if(attr=='theme'||attr=='instid'){
                data[attr]=urlCfg[attr];
            }
        }
        return api_common_openwindow.genURL(data);
        
    },
    delaySearch:function(){
        this.cacheData={};
        this.selectedData=[];
        this.unselectedData=[];
		var self=this;
		Util.DelayRun('screenerSearch.screener', function(){
			self.searchOperate(0);
		}, 1000, this);
    },
	_getHtml:function(){         
        var str='<div class="qs-screener">'+
                '<div class="qs-search-loading"></div>'+
                '<div class="qs-gd2">'+
                '<div class="bd">'+
                '<div class="qs-main"><div class="qs-c">'+
                '<div class="qs-screener-introduce"><h2>Screener</h2><p>Screener allows you to quickly find funds using the search criteria listed below. Select at least one criteria and then click the Show Results tab.</p></div>'+
                '<div class="qs-screener-operator"></div>'+
                '<div class="qs-screener-resultview"></div>'+
                '<div class="qs-screener-resultData"><div class="qs-no-info">No data available.</div></div>'+
                '<div class="qs-screener-pagination-bottom"></div>'+
                '</div></div>'+
                '<div class="qs-c">'+
                '<div class="qs-screener-universe"><div class="title"><h3>Universe:</h3></div></div>'+
                '<div class="qs-screener-fixedfilter"></div>'+
                '<div class="qs-screener-leftMenu"></div>'+
                '</div>'+
                '</div>'+
                '<div class="ft"></div>'+
                '</div>'
                '</div>';
                
        return str;
    },
    _getGridInitWH:function(){
        if(this.config.isAPI){
            w = this.config.width||this.container.width();
            h = this.config.height||this.container.height();
        }else{
            //if it is terminal, the height of win-bd is static
            w = this.config.width;
            h = this.config.height;
            h -=this.staticValue.winTitle;
        }
        return {height:(h -this.staticValue.viewTab- this.staticValue.pageBar - (this.config.needOperBar?this.staticValue.operateBar:0)),
                width:(w-this.staticValue.leftMenuWidth)};

    },
	genDataGrid:function(){
        if (!this.dataGrid) {
            var self=this;
            var wandh=this._getGridInitWH();
            this.dataGrid = new Util.DataGrid($('.qs-screener-resultData'), {}, {
                column: [],
                fixSize: true,
                htmlLayer: 'div',
                width:wandh.width,
                height:wandh.height,
                delayResize:false,
				rowDragDropGroup: 'gridDDGroup',
				rowDragable:this.config.dragable,
                autoHeight: !this.config.fixHeight,
                indexColKey: this.indexColKey
            }, {
                onCellMouseover: function(e, cell, row){
                
                },
                onCellMouseout: function(e, cell, row){
                
                },
				onRowDragStart: function(e, proxy, row){  // prevent the ticker is from the same component.
					//gridDDGroup
					var ticker=row.data[self.PIdCode];
					proxy.html(row.data[self.getCode(self.tickerCode)]);
					proxy._ticker=ticker;
					proxy._component="screener";
				},
                onSortedbyCell:function(cellkey,lastorder,callback){
                    var sorttype=lastorder=="ASC"?"2":"1";
                    self.cacheData={}//clear data cache
                    self.unselectedData=[];//clear unselectedData cache
                    self.selectedData=[];//clear selectedData cache
                    if (self.sortCache != self.getCode(cellkey) + ":" + sorttype) {
                        self.searchOperate(self.pageBottom.getCurrentInfo().start-1, self.getCode(cellkey), sorttype);
                    }
                },
                afterRebindData: function(DOMMap, rows){
                    self.changeOutSize();
                    self.heightChangeCB();
                },
                onCellClick:function(e,cell,row){
					if(!self.config.clickTicker) return;
                    if (cell.el.find("input").length > 0) return;
					var URL=self._getQuickTakeURL(row.data[self.PIdCode]);
                    if (typeof self.callback.onTickerClick == 'function') {
                        self.callback.onTickerClick({
                            component: "screeners",
                            ticker: row.data[self.PIdCode],
                            url: URL
                        });
                    }
                    else {
                        if (cell.dataType == 'link') {
                            api_common_openwindow.openWindow(URL,"Quicktake");
                        }
                    }
                }
            });
        }
    },
	genPage:function(){
        var self=this;
        this.pageBottom=new Util.PageUtil($('.qs-screener-pagination-bottom'),{
            onClick:function(startAt,endAt){
                self.searchOperate(startAt-1);
            }
        },{
            navSize:this.config.navSize,
            pageSize:this.config.pageSize,
            curPage:0,
            total:0
        });
    },
	genOperatoeBar:function(){
		var self=this;
        var operateBarConfig=this.operateBarConfig||this.config.operateBarConfig||{};
        if(!QSPC.checkPermission(25.01)){
            operateBarConfig["idr"]=false;
        }
		this.operateBar=new QS_SearchOperateBar($(".qs-screener-operator"),$.extend({
			"separator":" ",
            "name":true
			},this.operateBarConfig||this.config.operateBarConfig||{}),{
            "onNew":function(event){
				self.selectMySearch();
			},"onOpen":function(event){
               var data={
					type:self.templeteType,
					trigger:event,
					title:"",
					container:$('.qs-screener'),
					hightLight:[self.currentSearchItemID],
					onClick:function(e,data){
						self.selectMySearch(data.id);
					},
					afterShow:function(moredialog){
						self._bindUnMoreDialogEvent(moredialog);
					}
				};
				self.saveSearch.list(data);
            },"onSave":function(event){
                var saveddata = self.getSavedData();
				if (saveddata.cansave) {
					var sort=self.sortCache.split(":");
					saveddata.data.sorttype=sort[1];
					saveddata.data.sortfield=sort[0];
					self.saveSearch.save(self.currentSearchItemID,saveddata.data);
				}
			},"onSaveas":function(event){
                var saveddata = self.getSavedData();
				if (saveddata.cansave) {
					var sort=self.sortCache.split(":");
					saveddata.data.sorttype=sort[1];
					saveddata.data.sortfield=sort[0];
					self.saveSearch.saveAs(saveddata.data);
				}
			},"onDelete":function(event){
                var data={
					type:self.templeteType,
					trigger:event,
					title:"",
					container:$('.qs-screener'),
					hightLight:[self.currentSearchItemID],
					onClick:function(e,data){
						self.saveSearch.remove(data.id,"Delete screener");
					},
					afterShow:function(moredialog){
						self._bindUnMoreDialogEvent(moredialog);
					}
				};
				self.saveSearch.list(data);
			},"onPDF":function(event){
				self._exportToFile("pdf");
			},"onIDR":function(event){
				self._exportToFile("idr");
			},"onDefault":function(event){
				self.saveSearch.setDefault(self.currentSearchItemID);
			}
		});
	},
	_bindUnMoreDialogEvent:function(moreDialog){
		var self=this;
        self.el.unbind("click.moredialog").bind("click.moredialog",function(e){
            e.stopPropagation();
            var obj = $(e.target);
            var className = obj.attr("class")||"";
            if(className.indexOf(" ")!=-1){
                className = className.substring(0,className.indexOf(" "));
            }
            if(className!="open"&&className !="delete"){
                if ($(e.target).closest(".rtq-scrollbar").length == 0||$(e.target).closest(".qs-c").length>0) {
                    moreDialog.hide();
                    $('.qs-screener-operator .qs-screener-extend').removeClass('on');
                    self.el.unbind("click.moredialog");
                }
            }
        });
	},
	genViewTab:function(){
        if (this.viewTabmenu) {
            this.viewTabmenu.reBindData(this.viewTabData[this.curTabID]);
        }
        else {
            var self = this;
            this.viewTabmenu = new Util.TabMenu($('.qs-screener-resultview'), this.viewTabData[this.curTabID], {
                onActive: function(tab){
                    self.currentView = tab.id;
                    self.searchOperate(0);
                }
            }, {
                width: 80,
                isExcuteCallbackAtInit: false,
                tabsList: false,
                activeTabId: 0
            });
        }
        this.currentView=this.viewTabmenu.currentTab.id;
    },
	genGroupBox:function(){
        var self=this,groupbox=$(".qs-screener-leftMenu");
		this.removeAllRow();
        groupbox.empty();
        this.groupBox = new Util.GroupBox(groupbox,this.groupBoxCategory[this.curTabID],{
            width: this.staticValue.leftMenuWidth,
            autoHeight:true,
            animate:false,
            expendAll:true
        },{onClickHead:function(group){
			if (group.isShow) {
				self._bindDynamicFilterDOM(group.id);
			}else{
                self.setScreenerScroll();
            }
            self.heightChangeCB();
        }});
    },
    heightChangeCB:function(){
        var self=this;
        if (self.firstTag) {
            Util.DelayRun('onload.screener', self.loadHandler, 100, self);
        }
        else {
            Util.DelayRun('heightchange.screener', self.heightChangeHandler, 100, self);
        }
    },
    genDropDownList:function(){
        var self=this;
        this.dropDownList = new Util.DropDownList($('.qs-screener-universe')[0], function(t, v){
                if (self.curTabID != v) {
                    self.curTabID=v;
					self.removeAllRow();
					self.clearSelectedItem();
                    self.selectMySearch();
                }
            }, this.universeCategory,{
                    width: 150,
                    actionAtInit:false
        });
    }
});
var QS_Terminal_Screener=null;